<template>
  <!-- 学员报名弹窗 -->
  <el-dialog v-model="visible" title="学员报名" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="80px">
      <el-form-item prop="realName" label="姓名">
        <el-select v-model="dataForm.realName" placeholder="姓名" clearable filterable @clear="changeRealName" @change="changeRealName">
          <el-option v-for="(item,index) in realList" :key="index" :label="item.realName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="userTag" label="标签">
        <el-input v-model.trim="dataForm.userTag" placeholder="标签"></el-input>
      </el-form-item>
      <el-form-item prop="gender" label="性别">
        <el-radio-group v-model="dataForm.gender">
          <el-radio :value="0" size="large">男</el-radio>
          <el-radio :value="1" size="large">女</el-radio>
          <el-radio :value="2" size="large">保密</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="age" label="年龄">
        <el-input v-model.trim="dataForm.age" maxlength="3" placeholder="年龄" @input="(e)=>handleInput(e,1)"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="手机号">
        <el-input v-model.trim="dataForm.mobile" maxlength="11" placeholder="手机号" @input="(e)=>handleInput(e,2)"></el-input>
      </el-form-item>
      <el-form-item prop="courseId" label="课程">
        <el-select v-model="dataForm.courseId" placeholder="课程" clearable filterable @change="(e)=>changeCourse(e)" @clear="(e)=>changeCourse(e)">
          <el-option v-for="(item,index) in courseList" :key="index" :label="item.courseName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="payMoney" label="付款金额">
        <el-input v-model.trim="dataForm.payMoney" placeholder="付款金额" @input="(e)=>handleInput(e,3)"></el-input>
      </el-form-item>
      <el-form-item prop="school" label="就读学校">
        <el-input v-model.trim="dataForm.school" placeholder="就读学校"></el-input>
      </el-form-item>
      <el-form-item prop="payTime" label="支付时间">
        <el-date-picker v-model="dataForm.payTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="支付时间" style="width:100%;" />
      </el-form-item>
      <el-form-item prop="type" label="支付方式">
        <el-select v-model="dataForm.type" placeholder="支付方式" clearable>
          <el-option :value="0" label="微信支付" />
          <el-option :value="1" label="支付宝支付" />
        </el-select>
      </el-form-item>
      <el-form-item prop="headUrl" label="头像">
        <div class="updateImg-box">
          <updateImg ref="uploadRef" :urlList="dataForm.urlList" @updatImgList="updatImgList"></updateImg>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from "vue";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { ElMessage } from "element-plus";
import updateImg from "@/components/updateImg.vue";
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const uploadRef = ref();
const realList = ref([]);
const courseList = ref([]);

const dataForm = reactive<IObject>({
  id: "",
  realName: "",
  userTag: "",
  gender: 0,
  age: "",
  mobile: "",
  courseId: "",
  courseName: "",
  payMoney: "",
  school: "",
  payTime: "",
  type: null,
  headUrl: "",
  urlList: []
});

// 校验手机号输入
const validatorPhone = (rule: any, value: any, callback: any) => {
  let ver = /^1[0-9]{10}$/; //以1开头
  if (value === "") {
    callback(new Error("必填项不能为空"));
  } else if (!ver.test(value)) {
    callback(new Error("请填写正确的手机号"));
  } else {
    callback();
  }
};

const rules = ref({
  realName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  userTag: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  age: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  mobile: [{ required: true, validator: validatorPhone, trigger: "blur" }],
  gender: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  courseId: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  payMoney: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  payTime: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  type: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  headUrl: [{ required: true, message: "必填项不能为空", trigger: "change" }]
});

const init = async (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataForm.urlList = [];
    dataFormRef.value.resetFields();
  }
  await getRealList();
  await getCourseList();

  await nextTick(() => {
    uploadRef.value.init();
  });
};

// 获取学员列表
const getRealList = () => {
  baseService
    .get(`/lingyao/student/page`, {
      page: 1,
      limit: 10000
    })
    .then((res) => {
      realList.value = res.data.list;
    });
};

// 获取课程列表
const getCourseList = () => {
  baseService
    .get(`/lingyao/courseinfo/page`, {
      page: 1,
      limit: 10000
    })
    .then((res) => {
      courseList.value = res.data.list;
    });
};

// 监听姓名选择
const changeRealName = (val: any) => {
  let len = realList.value.filter((item: any) => item.id == val) as any[];
  if (len.length > 0) {
    dataForm.gender = len[0].gender;
    dataForm.age = len[0].age;
    dataForm.mobile = len[0].mobile;
    dataForm.school = len[0].school;
    dataForm.headUrl = len[0].headUrl;
    dataForm.urlList = [
      {
        name: "头像",
        url: len[0].headUrl
      }
    ];
  } else {
    dataForm.gender = 0;
    dataForm.age = "";
    dataForm.mobile = "";
    dataForm.school = "";
    dataForm.headUrl = "";
    dataForm.urlList = [];
  }
  nextTick(() => {
    uploadRef.value.init();
  });
};

// 监听课程列表
const changeCourse = (val: any) => {
  let len = (courseList.value.filter((item: any) => item.id == val) as IObject[]) || [];
  dataForm.courseName = len.length > 0 ? len[0].courseName : "";
};

// 处理年龄和手机号,金额只能输入正整数
const handleInput = (val: any, type: number) => {
  // 使用正则表达式过滤非数字字符
  let inputValue;
  inputValue = val.replace(/\D/g, "");

  if (type == 1) {
    dataForm.age = inputValue;
  } else if (type == 2) {
    dataForm.mobile = inputValue;
  } else {
    dataForm.payMoney = inputValue;
  }
};

// 上传图片成功
const updatImgList = (list: any[]) => {
  dataForm.headUrl = list.length > 0 ? list[0].url : "";
  dataForm.urlList = list;
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/lingyao/student/studentSignUp", dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
